package com.funny.stock.data.service;

import com.funny.stock.base.service.BaseCrudService;
import com.funny.stock.data.dao.entity.StockDO;
import com.funny.stock.data.dao.repo.StockRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Component
public class StockService extends BaseCrudService<StockDO,Long> {

    @Autowired
    StockRepository repository;

    @Override
    protected JpaRepository<StockDO, Long> setupJpaRepository() {
        return repository;
    }

    public Page<StockDO> findPageByKey(String key, PageRequest pageRequest){
        return repository.findAll(createSpecification(key), pageRequest);
    }

    public StockDO findByCode(String code){
        return repository.findByCode(code);
    }

    private Specification<StockDO> createSpecification(String key) {
        return (Specification<StockDO>) (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();

            if(!StringUtils.isEmpty(key)) {
                predicateList.add(cb.or(cb.like(root.get("name"), "%" + key + "%"),
                        cb.like(root.get("code"), "%" + key + "%")));
            }

            return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

        };

    }

}
